package com.lagou.demo.Filter;

import com.lagou.demo.pojo.User;
import com.lagou.demo.service.LoginService;
import com.lagou.demo.service.UserService;
import com.lagou.demo.util.CookieUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        UserService userService = new UserService();
        if(request.getRequestURI().contains("index")){
            chain.doFilter(req, resp);
            return;
        }else {
            String username =(String) request.getSession().getAttribute("username");
            if(username==null) {//session中没有，去Cookie中找
                String val = CookieUtil.getCookieValByKey("auto", request);
                if(val!= null&& !val.equals("")) {
                    String name = val.split("_")[0];
                    String pass = val.split("_")[1];
                    if(new LoginService().login(new User(name,pass))) {//重新验证登录
                        request.getSession().setAttribute("username", name);//登录成功，放入Session，并放行
                        chain.doFilter(request, response);
                        return;
                    }else {//验证失败，重新登录
                        response.sendRedirect("index.jsp");
                    }
                }else {//Cookie中也没有，第一次访问，跳转登录页面
                    response.sendRedirect("index.jsp");
                }
            }else {//session中有，放行
                chain.doFilter(request, response);
                return;
            }
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
